<?php
/**
 * 推荐位内容后台管理
 * @author liubo <liubo@ilongyuan.com.cn>
 */
namespace Admin\Controller;

class PosDataController extends BaseManageController {
    /**
    *控制操作的模型表
    */
    protected $modelName = 'PosData';

    /**
    *删除类型的设置 true|直接删除， false|设置数据状态
    */
    protected $is_del   = true;

    /**
    *跳转的Url
    */
    protected $jumpAct  = 'Pos/index';

    public function _initialize()
    {
        parent::_initialize();
        $posId = I('posId', 0, 'intval');
        $this->pos = service('Pos')->find($posId);
        $this->jumpAct = U('Pos/items', ['id' => $posId]);
    }

    public function add()
    {
        if (!$this->pos) {
            $this->error('参数错误');
        }
        $types = C('POS_TYPES');
        $this->type_str = $types[$this->pos['type']];
        if (IS_POST) {
            switch ($this->pos['type']) {
                case 'video':
                    $event = event('Video');
                    break;
                case 'user':
                    $event = event('User');
                    break;
                case 'race':
                    $event = event('RaceGroup');
                    break;
                case 'goods':
                    $event = event('MallGoods');
                    break;
                case 'news':
                    $event = event('News');
                    break;
            }
            $target_id = I('target_id');
            $target_obj = $event->info($target_id);
            if (!$target_id || !$target_obj['id']) {
                $this->error("{$this->type_str}不存在或已经被删除");
            }

            $data = [
                'target_id' => $target_id,
                'pos_id'    => $this->pos['id'],
                'pos_code'  => $this->pos['code'],
                'type'      => $this->pos['type']
            ];
            if ($this->model->where($data)->find()) {
                $this->error("该{$this->type_str}已被推荐");
            }
            $data['sort'] = 0;
            $data = $this->model->create($data);

            if ($data) {
                unset($data['id']);
            }
            if ($data && $this->model->add($data)) {
                // 删除了jumpAct调用U函数  ini里已经做了
                $this->_after_add($data);
                $this->success('操作成功!', $this->jumpAct);
            } else {
                $this->error($this->model->getError());
            }
        } else {
            $this->display('form');
        }
    }
}